package com.example.gcode;

import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.ListActivity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.gcloud.dashboard.Dashboard;
import com.gcloud.dashboard.Favoritos;
import com.gcloud.dropbox.DeleteDropBoxFileActivity;
import com.gcloud.dropbox.DownloadDropBoxFileActivity;
import com.gcloud.dropbox.DownloadDropBoxfile;
import com.gcloud.dropbox.UploadDropBoxFileActivity;
import com.gcloud.dto.GCloudFile;
import com.gcloud.googledrive.DeleteGoogleFileActivity;
import com.gcloud.googledrive.DownloadGoogleFileActivity;
import com.gcloud.googledrive.UploadGoogleFileActivity;
import com.gcloud.login.Login;
import com.gcloud.persistance.SQLiteHandler;
import com.gfilechooser.utils.FileUtils;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.services.drive.Drive;
import com.utils.Constants;
import com.utils.GCloudUtil;
import com.utils.Message;
import com.dropbox.client2.android.AndroidAuthSession;
import com.dropbox.client2.DropboxAPI;

public class Archivos extends ListActivity {

	private static final String TAG_NOMBRE = "TAG_NOMBRE";
	private static final String TAG_FILE_ID = "TAG_FILE_ID";
	private static final String TAG_DESCRIPTION = "TAG_DESCRIPTION";
	private static final String TAG_ACCOUNT = "TAG_ACCOUNT";
	private static final String TAG_IS_DIRECT = "TAG_IS_DIRECT";
	Drive service;
	GoogleAccountCredential credential;
	private static final int REQUEST_CODE = 100;
	String root = "";
	private SQLiteHandler sqliteHandler = new SQLiteHandler(Archivos.this,
			Constants.GCLOUD, null, Constants.DB_VERSION);

	/* DROP BOX THINGS */
	DropboxAPI<AndroidAuthSession> mApi;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.archivos_list);
		registerForContextMenu(getListView());
		if(!getKeys()){
			redirectToLogin();
		}
		
		// credential = GoogleAccountCredential.usingOAuth2(
		// this, DriveScopes.DRIVE);
		// startActivityForResult(credential.newChooseAccountIntent(),
		// REQUEST_ACCOUNT);
		// dropBoxAuthentication();
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			String newRoot = bundle.getString("initRoot");
			if (newRoot != null)
				root = newRoot;
			Log.i("From archivos bundle", "" + root);
		}
		showFilesOnUi();
		// listFiles();
		// TextView texView=(TextView)findViewById(R.id.list_service);
		// if(texView.isShown()){
		// Log.i("textview","going to be invisible");
		// texView.setVisibility(View.INVISIBLE);
		// }else{
		// Log.i("textview","is invisible");
		// }

	}
	
	public boolean getKeys() {
		SharedPreferences prefs = getSharedPreferences(
				Constants.gBoxSharedProperties, 0);
		String key = prefs.getString(Constants.trueAnswer,
				Constants.falseAnswer);
		return key != null && key.equals(Constants.trueAnswer);

	}
	
	public void redirectToLogin() {
		Intent DashboardDes = new Intent(getApplicationContext(),
				Login.class);
		DashboardDes.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(DashboardDes);
		finish();
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.contextmenu, menu);
		Log.i("este tag", " si furula");
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		GCloudFile fileSelected = filesItems.get((int) info.id);
		switch (item.getItemId()) {
		case R.id.menu_bookmark:// Favorite
			int favoriteRate = fileSelected.getFavoriteRate();
			favoriteRate += 1;
			sqliteHandler.checkAsFavorite(fileSelected.getKey(), favoriteRate);
			showToast(MessageFormat.format(Message.IS_NEW_FAVORITE,
					fileSelected.getName()));
			return true;
		case R.id.menu_search:// Drop
			if (fileSelected.getService().equals(Constants.GOOGLE)) {
				Intent deleteIntent = new Intent(getApplicationContext(),
						DeleteGoogleFileActivity.class);
				deleteIntent
						.putExtra(Constants.FILE_KEY, fileSelected.getKey());
				startActivity(deleteIntent);
			} else {
				Intent deleteDropBoxFile = new Intent(getApplicationContext(),
						DeleteDropBoxFileActivity.class);
				deleteDropBoxFile.putExtra(Constants.FILE_URL, fileSelected
						.getUri().toString());
				startActivity(deleteDropBoxFile);
			}
			showToast(MessageFormat.format(Message.FILE_DELETED,
					fileSelected.getName()));
			return true;
		case R.id.menu_save:// Download
			Log.i("menu SAVE", fileSelected.getName());
			if (fileSelected.getService().equals(Constants.DROPBOX)) {
				Log.i("Archivos open file: ",
						"DropBox file: " + fileSelected.getUrl());
				Intent intent = new Intent(getApplicationContext(),
						DownloadDropBoxFileActivity.class);
				intent.putExtra(Constants.FILE_URL, fileSelected.getUrl());
				intent.putExtra(Constants.FILE_NAME, fileSelected.getName());
				intent.putExtra(Constants.FILE_ACCOUNT,
						fileSelected.getAccount());
				startActivity(intent);
			} else {
				// TODO send to download file from google drive
				Log.i("Archivos open file: ", "GoogleDrive file");
				Intent intent = new Intent(getApplicationContext(),
						DownloadGoogleFileActivity.class);
				intent.putExtra(Constants.FILE_KEY, fileSelected.getKey());
				intent.putExtra(Constants.FILE_URL, fileSelected.getUrl());
				intent.putExtra(Constants.FILE_ACCOUNT,
						fileSelected.getAccount());
				intent.putExtra(Constants.FILE_NAME, fileSelected.getName());
				intent.putExtra(Constants.FILE_MIMETYPE,
						fileSelected.getMimeType());
				startActivity(intent);
			}
			return true;
			// showToast("menu save=desc: " + fileSelected.getName());
		case R.id.menu_upload:
			if (fileSelected.getService().equals(Constants.GOOGLE)) {
				Log.i("here", "google drive");
				Intent intentGF = new Intent(Archivos.this,
						UploadGoogleFileActivity.class);
				intentGF.putExtra(Constants.FILE_PARENT, root);
				startActivity(intentGF);
			} else {
				Log.i("here", "dropbox");
				Intent intentDF = new Intent(Archivos.this,
						UploadDropBoxFileActivity.class);
				intentDF.putExtra(Constants.FILE_PARENT, root);
				startActivity(intentDF);
			}
			return true;
			// actionIntent = new Intent(Archivos.this,
			// DownloadGoogleFileActivity.class);
			// actionIntent.putExtra(Constants.FILE_KEY, lista.get((int)
			// info.id)
			// .get(TAG_FILE_ID));
			// startActivity(actionIntent);
		default:
			return super.onContextItemSelected(item);
		}

	}

	private String fileClicked = "";

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		GCloudFile gFile = filesItems.get(position);
		String item = gFile.getKey();// lista.get(position).get(TAG_FILE_ID);
		boolean isDirectory = gFile.isDirectory();
		// GCloudUtil.equals("true", lista.get(position)
		// .get(TAG_IS_DIRECT), false);
		// SQLiteHandler sqliteHandler = new SQLiteHandler(Archivos.this,
		// Constants.GCLOUD, null, Constants.DB_VERSION);
		String mes = "Item: " + item + " : Is Directory: " + isDirectory;
		Log.i("Archivos: ", mes);
		// showToast(mes);
		// sqliteHandler.getFile(item);
		if (item.equalsIgnoreCase(fileClicked)) {
			if (isDirectory) {
				// root = gFile.getParent();
				if (gFile.getService().equalsIgnoreCase(Constants.DROPBOX)) {
					root = gFile.getUrl() + Constants.DROPBOX_ROOT;
				} else {
					root = item;
				}
				Log.i("Archivos new root: ", " " + root);
				Intent inte = new Intent(getApplicationContext(),
						Archivos.class);
				inte.putExtra("initRoot", root);
				startActivity(inte);
				// showToast("click on directory: " +
				// item+" : "+gFile.getName());
			} else {

				if (gFile.getService().equals(Constants.DROPBOX)) {
					// TODO send to download file from dropbox
					Log.i("Archivos open file: ", "DropBox file");
					Intent intent = new Intent(getApplicationContext(),
							DownloadDropBoxFileActivity.class);
					intent.putExtra(Constants.FILE_URL, gFile.getUrl());
					intent.putExtra(Constants.FILE_NAME, gFile.getName());
					intent.putExtra(Constants.FILE_ACCOUNT, gFile.getAccount());
					startActivity(intent);
				} else if (gFile.getService().equals(Constants.GOOGLE)) {
					// TODO send to download file from google drive
					Log.i("Archivos open file: ", "GoogleDrive file");
					Intent intent = new Intent(getApplicationContext(),
							DownloadGoogleFileActivity.class);
					intent.putExtra(Constants.FILE_KEY, gFile.getKey());
					intent.putExtra(Constants.FILE_URL, gFile.getUrl());
					intent.putExtra(Constants.FILE_ACCOUNT, gFile.getAccount());
					intent.putExtra(Constants.FILE_NAME, gFile.getName());
					intent.putExtra(Constants.FILE_MIMETYPE,
							gFile.getMimeType());
					startActivity(intent);
				}
			}
			fileClicked = "";
		} else {
			fileClicked = item;
		}

	}

	/**
	 * Support for doble click
	 */

	// @Override
	// protected void onListItemClick(ListView l, View v, int position, long id)
	// {
	// super.onListItemClick(l, v, position, id);
	// String item = lista.get(position).get(TAG_FILE_ID);
	// boolean isDirectory=GCloudUtil.equals("true",
	// lista.get(position).get(TAG_IS_DIRECT), false);
	// if (item.equalsIgnoreCase(fileClicked)) {
	// showToast("doble click on: " + item);
	// fileClicked = "";
	// } else {
	// fileClicked = item;
	// }
	// }

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_upload:

			Log.i("here", "upload");
			// showChooser();
			break;
		case R.id.menu_download:
			Log.i("here", "download");
			Intent returnIntent = new Intent(Archivos.this, Dashboard.class);
			startActivity(returnIntent);
			finish();
			break;
		case R.id.menu_delete:
			Log.i("here", "delete");
			break;
		case R.id.menu_bookmark:
			Log.i("here", "bookmark");
			break;
		case R.id.menu_save:
			Log.i("here", "save");
			break;
		case R.id.menu_search:
			Log.i("here", "search");
			break;
		case R.id.menu_google_drive_sy:
			Log.i("here", "google drive");
			// SQLiteHandler lite=new SQLiteHandler(Archivos.this,
			// Constants.GCLOUD, null, Constants.DB_VERSION);
			// try {
			// lite.getSavedList();
			// } catch (SQLException e) {
			// Log.i("Exception arch: ",e.getMessage());
			// }
			// TODO this is good, I'm going to try the insert method manual
			Intent intentnew = new Intent(Archivos.this,
					GoogleDriveSyncronized.class);
			startActivity(intentnew);
			break;
		case R.id.menu_dropbox_sy:
			Log.i("here", "dropbox");
			Intent intentdrop = new Intent(Archivos.this,
					DropBoxSyncronized.class);
			startActivity(intentdrop);
			break;
		case R.id.menu_google_drive:
			Log.i("here", "por nombre");

			// Intent intentGF = new Intent(Archivos.this,
			// UploadGoogleFileActivity.class);
			// startActivity(intentGF);
			break;
		case R.id.menu_dropbox:
			Log.i("here", "por cuenta");

			// Intent intentDF = new Intent(Archivos.this,
			// UploadDropBoxFileActivity.class);
			// startActivity(intentDF);
			break;
		case R.id.menu_salir:
			Log.i("here", "salir");
			storeLoggin();
			Intent intentOut = new Intent(Archivos.this, Login.class);
			startActivity(intentOut);
			break;
		}
		return true;
	}

	public void storeLoggin() {
		SharedPreferences prefs = getSharedPreferences(
				Constants.gBoxSharedProperties, 0);
		Editor edit = prefs.edit();
		edit.putString(Constants.trueAnswer, Constants.falseAnswer);
		edit.commit();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.layout.menu_layout, menu);
		return true;
	}

	ArrayList<HashMap<String, String>> lista = new ArrayList<HashMap<String, String>>();
	List<GCloudFile> filesItems = new ArrayList<GCloudFile>();

	private void listFiles() {

		for (int i = 0; i < 8; i++) {
			HashMap<String, String> map = new HashMap<String, String>();

			map.put(TAG_NOMBRE, "prueba" + i);
			map.put(TAG_FILE_ID, "KEY: " + i);
			map.put(TAG_DESCRIPTION, "DESCRIPTION FILE: File number " + i);
			map.put(TAG_ACCOUNT, "GMAIL OR DROPBOX its something");
			lista.add(map);
		}
		// ListAdapter adapter = new SimpleAdapter(Archivos.this, lista,
		// R.layout.archivos_list_item, new String[] { TAG_NOMBRE,
		// TAG_FILE_ID, TAG_DESCRIPTION, TAG_ACCOUNT }, new int[] {
		// R.id.list_nombre, R.id.list_key, R.id.list_service,
		// R.id.list_account });
		// setListAdapter(adapter);

	}

	private void showFilesOnUi() {
		List<GCloudFile> fileList = new ArrayList<GCloudFile>();
		try {
			// TODO is ok, is just to accelerate the charge of files
			if (root == null || root.equals("")) {
				Log.i("Archivos: ",
						"root is null or empty, going to charge static list");
				// GCloudSingleton gCloudSingleton =
				// GCloudSingleton.getInstance();
				// fileList = gCloudSingleton.getFilesFromAllService();
				fileList = sqliteHandler.getFileList(Constants.FILE_IS_ROOT
						+ "=? or " + Constants.FILE_PARENT + "= ?",
						new String[] { "1", Constants.DROPBOX_ROOT });
			} else {
				Log.i("Archivos:", "root is not empthy goig to charge query");
				fileList = sqliteHandler.getFileList("PARENT=?",
						new String[] { root });
			}

		} catch (SQLException e) {
			fileList = new ArrayList<GCloudFile>();
		}
		filesItems = fileList;
		// for (GCloudFile gCloudFile : fileList) {
		// HashMap<String, String> mapUI = new HashMap<String, String>();
		// mapUI.put(TAG_NOMBRE, gCloudFile.getName());
		// mapUI.put(TAG_FILE_ID, gCloudFile.getKey());
		// mapUI.put(TAG_DESCRIPTION, gCloudFile.getSize() + " Bytes");
		// mapUI.put(TAG_ACCOUNT, gCloudFile.getAccount());
		// mapUI.put(TAG_IS_DIRECT, "" + gCloudFile.isDirectory());
		// lista.add(mapUI);
		// }

		// ArrayList<HashMap<String, String>> lista = new
		// ArrayList<HashMap<String, String>>();
		// for (int i = 0; i < 8; i++) {
		// HashMap<String, String> map = new HashMap<String, String>();
		//
		// map.put(TAG_NOMBRE, "prueba" + i);
		// map.put(TAG_FILE_ID, "Google Drive");
		// lista.add(map);
		// }

		ArrayAdapter<GCloudFile> newAdapter = new GCloudAdapter();

		/*
		 * ListAdapter adapter = new SimpleAdapter(Archivos.this, lista,
		 * R.layout.archivos_list_item, new String[] { TAG_NOMBRE, TAG_FILE_ID,
		 * TAG_DESCRIPTION, TAG_ACCOUNT, TAG_IS_DIRECT }, new int[] {
		 * R.id.list_nombre, R.id.list_key, R.id.list_service,
		 * R.id.list_account, R.id.list_isfile });
		 */
		setListAdapter(newAdapter);

	}

	// private void clickSupport() {
	// ListView list = getListView();
	// list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
	// @Override
	// public void onItemClick(AdapterView<?> parent, View viewClicked,
	// int position, long id) {
	//
	// }
	// });
	// }

	private class GCloudAdapter extends ArrayAdapter<GCloudFile> {

		public GCloudAdapter() {
			super(Archivos.this, R.layout.archivos_list_item, filesItems);
			// TODO Auto-generated constructor stub
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View viewItem = convertView;
			if (viewItem == null) {
				viewItem = getLayoutInflater().inflate(
						R.layout.archivos_list_item, parent, false);
			}
			GCloudFile currentFile = filesItems.get(position);
			ImageView imageFileType = (ImageView) viewItem
					.findViewById(R.id.img_fileType);
			imageFileType.setImageResource(currentFile.getFileTypeIcon());
			ImageView imageService = (ImageView) viewItem
					.findViewById(R.id.img_servicio);
			imageService.setImageResource(currentFile.getServiceIcon());
			TextView textViewName = (TextView) viewItem
					.findViewById(R.id.list_nombre);
			textViewName.setText(currentFile.getName());
			TextView textViewService = (TextView) viewItem
					.findViewById(R.id.list_service);
			textViewService.setText(currentFile.getSize() + " Bytes");
			// TextView
			// textViewKey=(TextView)viewItem.findViewById(R.id.list_key);
			// textViewKey.setText(currentFile.getKey());
			// TextView
			// textViewAccount=(TextView)viewItem.findViewById(R.id.list_account);
			// textViewAccount.setText(currentFile.getAccount());
			// TextView
			// textViewFile=(TextView)viewItem.findViewById(R.id.list_isfile);
			// textViewFile.setText(""+currentFile.isDirectory());
			return viewItem;
		}

	}

	// private void showFilesOnUi() {
	// GCloudSingleton gCloudSingleton = GCloudSingleton.getInstance();
	// List<GCloudFile> fileList = gCloudSingleton.getFilesFromAllService();
	// // ArrayList<HashMap<String, String>> lista = new
	// // ArrayList<HashMap<String, String>>();
	// if (fileList.isEmpty()) {
	// return;
	// }
	// for (GCloudFile gCloudFile : fileList) {
	// HashMap<String, String> mapUI = new HashMap<String, String>();
	// mapUI.put(TAG_NOMBRE, gCloudFile.getName());
	// mapUI.put(TAG_FILE_ID, gCloudFile.getKey());
	// mapUI.put(TAG_DESCRIPTION, gCloudFile.getSize()+" Bytes");
	// mapUI.put(TAG_ACCOUNT, gCloudFile.getAccount());
	// mapUI.put(TAG_IS_DIRECT, ""+gCloudFile.isDirectory());
	// lista.add(mapUI);
	// }
	//
	// // ArrayList<HashMap<String, String>> lista = new
	// // ArrayList<HashMap<String, String>>();
	// // for (int i = 0; i < 8; i++) {
	// // HashMap<String, String> map = new HashMap<String, String>();
	// //
	// // map.put(TAG_NOMBRE, "prueba" + i);
	// // map.put(TAG_FILE_ID, "Google Drive");
	// // lista.add(map);
	// // }
	//
	// ListAdapter adapter = new SimpleAdapter(Archivos.this, lista,
	// R.layout.archivos_list_item, new String[] { TAG_NOMBRE,
	// TAG_FILE_ID, TAG_DESCRIPTION, TAG_ACCOUNT, TAG_IS_DIRECT }, new int[] {
	// R.id.list_nombre, R.id.list_key, R.id.list_service,
	// R.id.list_account, R.id.list_isfile });
	// setListAdapter(adapter);
	//
	// }

	// private void dropBoxAuthentication() {
	// AndroidAuthSession session = buildSession();
	// mApi = new DropboxAPI<AndroidAuthSession>(session);
	// checkAppKeySetup();
	// if (Archivos.mLoggedIn) {
	// Log.i("v()", "is still logged");
	// callDropBoxList();
	// } else {
	// Log.i("DropBoxAuthentication()", "is not logged");
	// mApi.getSession().startAuthentication(Archivos.this);
	// }
	// setLoggedIn(mApi.getSession().isLinked());
	// Log.i("DropBoxAuthentication", "Logged: "
	// + mApi.getSession().isLinked());
	// showToast("Logged: " + mApi.getSession().isLinked());
	// }

	// private void callDropBoxList() {
	// Log.i(TAG, "before to list");
	// ListDropBoxFile listDropBox = new ListDropBoxFile(Archivos.this, mApi,
	// "/");
	// Log.i(TAG, "before to execute");
	// listDropBox.execute();
	// Log.i(TAG, "after execute");
	// }

	// @Override
	// protected void onActivityResult(int requestCode, int resultCode, Intent
	// data) {
	// switch (requestCode) {
	// case REQUEST_ACCOUNT:
	// if (resultCode == RESULT_OK && data != null
	// && data.getExtras() != null) {
	// String accountName = data
	// .getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
	// credential.setSelectedAccountName(accountName);
	// service = getDriveServices(credential);
	// new CargarArchivos().execute();
	// Log.i("GCLOUD", "Ya entre a doInBackground :)");
	// // ListGoogleFile listGoogle = new ListGoogleFile(service,
	// // getApplicationContext());
	// Log.i("OnActivitty", "before to execute");
	// // try {
	// // listGoogle.execute();
	// // showFilesOnUi();
	// // } catch (Exception e) {
	// // Log.i("Exception catch", e.toString());
	// // // startActivityForResult(credential.newChooseAccountIntent(),
	// // // REQUEST_CONFIRMATION);
	// // }
	// Log.i("OnActivitty", "after execute");
	//
	// }
	// break;
	// case REQUEST_CODE:
	// if (resultCode == RESULT_OK) {
	// if (data != null) {
	// // Get the URI of the selected file
	// final Uri uri = data.getData();
	// try {
	// // Create a file instance from the URI
	// final File file = FileUtils.getFile(uri);
	// showToast("File selected: " + file.getAbsolutePath());
	// // UploadDropboxFile uploadDropBoxFile = new
	// // UploadDropboxFile(
	// // Archivos.this, mApi, "/", file);
	// // uploadDropBoxFile.execute();
	// UploadGoogleFile googleFile = new UploadGoogleFile(
	// service, Archivos.this, file);
	// googleFile.execute();
	// } catch (Exception e) {
	// Log.e("FileSelectorTestActivity", "File select error",
	// e);
	// }
	// }
	// }
	// break;
	// // case REQUEST_CONFIRMATION:
	// // startActivityForResult(credential.newChooseAccountIntent(),
	// // REQUEST_ACCOUNT);
	// // break;
	// }
	// }

	@Override
	protected void onResume() {
		super.onResume();
		// if (mApi.getSession() == null) {
		// Log.i("onResume()", "session null");
		// return;
		// }
		// AndroidAuthSession session = mApi.getSession();
		//
		// if (session.authenticationSuccessful()) {
		// try {
		// session.finishAuthentication();
		// TokenPair tokens = session.getAccessTokenPair();
		// storeKeys(tokens.key, tokens.secret);
		// setLoggedIn(true);
		// } catch (IllegalStateException e) {
		// showToast("Couldn't authenticate with Dropbox:"
		// + e.getLocalizedMessage());
		// Log.i(TAG, "Error authenticating", e);
		// }
		// }
	}

	// private Drive getDriveServices(GoogleAccountCredential credential) {
	// return new Drive.Builder(AndroidHttp.newCompatibleTransport(),
	// new GsonFactory(), credential).build();
	// }

	public void showToast(final String toast) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(getApplicationContext(), toast,
						Toast.LENGTH_SHORT).show();
			}
		});
	}

	// public void checkAppKeySetup() {
	// if (APP_KEY.startsWith("CHANGE") || APP_SECRET.startsWith("CHANGE")) {
	// showToast("You must apply for an app key and secret from developers.dropbox.com, and add them to the GCloud ap before trying it.");
	// return;
	// }
	// Intent testIntent = new Intent(Intent.ACTION_VIEW);
	// String scheme = "db-" + APP_KEY;
	// String uri = scheme + "://" + AuthActivity.AUTH_VERSION + "/test";
	// testIntent.setData(Uri.parse(uri));
	// PackageManager pm = getPackageManager();
	// if (0 == pm.queryIntentActivities(testIntent, 0).size()) {
	// showToast("URL scheme in your app's "
	// + "manifest is not set up correctly. You should have a "
	// + "com.dropbox.client2.android.AuthActivity with the "
	// + "scheme: " + scheme);
	// }
	// }

	// public AndroidAuthSession buildSession() {
	// AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);
	// AndroidAuthSession session;
	//
	// String[] stored = getKeys();
	// if (stored != null) {
	// Log.i("buildSession", " getting key stored:");
	// AccessTokenPair accessToken = new AccessTokenPair(stored[0],
	// stored[1]);
	// session = new AndroidAuthSession(appKeyPair, AccessType.DROPBOX,
	// accessToken);
	// } else {
	// Log.i("buildSession",
	// "getting key not stored, going to build a new one");
	// session = new AndroidAuthSession(appKeyPair, AccessType.DROPBOX);
	// }
	// if (session != null) {
	// Log.i("buildSession", " session is not null");
	// }
	// return session;
	// }
	//
	// public String[] getKeys() {
	// SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
	// String key = prefs.getString(ACCESS_KEY_NAME, null);
	// String secret = prefs.getString(ACCESS_SECRET_NAME, null);
	// if (key != null && secret != null) {
	// String[] ret = new String[2];
	// ret[0] = key;
	// ret[1] = secret;
	// return ret;
	// } else {
	// return null;
	// }
	// }
	//
	// public void setLoggedIn(boolean loggedIn) {
	// Archivos.mLoggedIn = loggedIn;
	// Log.i("setLoggedIn() ", String.valueOf(mLoggedIn));
	// }
	//
	// public void storeKeys(String key, String secret) {
	// // Save the access key for later
	// SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
	// Editor edit = prefs.edit();
	// edit.putString(ACCESS_KEY_NAME, key);
	// edit.putString(ACCESS_SECRET_NAME, secret);
	// edit.commit();
	// }
	//
	// class CargarArchivos extends AsyncTask<String, String, String> {
	//
	// /**
	// * Before starting background thread Show Progress Dialog
	// * */
	// @Override
	// protected void onPreExecute() {
	// super.onPreExecute();
	// pDialog = new ProgressDialog(Archivos.this);
	// pDialog.setMessage("cargando archivos ...");
	// pDialog.setIndeterminate(false);
	// pDialog.setCancelable(false);
	// pDialog.show();
	// }
	//
	// GCloudSingleton gCloudSingleton;
	// /**
	// * getting Inbox JSON
	// * */
	// protected String doInBackground(String... voids) {
	//
	// Log.i("GCLOUD", "Ya entre a doInBackground :)");
	//
	// // new ListGoogleFile(service, getApplicationContext()).execute();
	//
	// // return "true";
	// List<com.google.api.services.drive.model.File> result = new
	// ArrayList<com.google.api.services.drive.model.File>();
	// Files.List request = null;
	// try {
	// request = service.files().list();
	// Log.i("retrieveAllFiles()", "getting files");
	// } catch (IOException e1) {
	// Log.i("retrieveAllFiles()", "something goes really wrong");
	// }
	// Log.i("retrieveAllFiles()", "to execute get Files");
	// if (request == null) {
	// Log.i("retrieveAllFiles() inside run",
	// "to execute get Files inside run");
	// return "false";
	// }
	// Log.i("retrieveAllFiles()", "request well formed ");
	// do {
	// try {
	// Log.i("ListGoogleFile", "Getting files");
	// FileList files = request.execute();
	// result.addAll(files.getItems());
	// request.setPageToken(files.getNextPageToken());
	// Log.i("ListGoogleFile", "Getting files at the end");
	// } catch (SocketException s) {
	// Log.i("ListGoogleFile", " SocketException: " + s);
	// return "false";
	// } catch (IOException e) {
	// System.out.println("An error occurred: " + e);
	// request.setPageToken(null);
	// return "false";
	// }
	// } while (request.getPageToken() != null
	// && request.getPageToken().length() > 0);
	// // TODO call singleton here
	//
	// if (result != null) {
	// gCloudSingleton = GCloudSingleton.getInstance();
	// gCloudSingleton.setFilesFromAllService(GCloudUtil
	// .googleFilesToGCloudFiles(result));
	// }
	// // String datasFromFilesD = "";
	// for (com.google.api.services.drive.model.File file : result) {
	// // datasFromFilesD += file.getTitle() + "  ";
	// Log.i("RetrieveAllFiles", "File title: " + file.getTitle());
	// }
	// // showToast(datasFromFilesD);
	// return "true";
	// }
	//
	// /**
	// * After completing background task Dismiss the progress dialog
	// * **/
	// protected void onPostExecute(String file_url) {
	// // dismiss the dialog after getting all products
	// pDialog.dismiss();
	// if(file_url.equalsIgnoreCase("true")){
	// showToast("everything well done");
	// }else{
	// showToast("probably something goes wrong");
	// }
	// // if(){
	// // startActivityForResult(credential.newChooseAccountIntent(),
	// // REQUEST_ACCOUNT);
	// // }
	// // updating UI from Background Thread
	// runOnUiThread(new Runnable() {
	// public void run() {
	// /**
	// * Updating parsed JSON data into ListView
	// * */
	// showFilesOnUi();
	// // GCloudSingleton gSingleton =
	// // GCloudSingleton.getInstance();
	// // Log.i("Archivos:", " "
	// // + gSingleton.getFilesFromAllService().size());
	// // ListAdapter adapter = new SimpleAdapter(Archivos.this,
	// // gSingleton.getFilesFromAllService(),
	// // R.layout.archivos_list_item, new String[] {
	// // TAG_NOMBRE, TAG_FILE_ID }, new int[] {
	// // R.id.list_nombre, R.id.list_service });
	// // updating listview
	// // setListAdapter(adapter);
	// }
	// });
	//
	// }
	//
	// }
}